package com.primaryedu.ui.inform;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.adapter.InformAdapter;
import com.primaryedu.bean.NoticeBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.HtmlActivity;
import com.primaryedu.widget.MyListView;
import com.primaryedu.widget.PullToRefreshView;
import com.primaryedu.widget.PullToRefreshView.OnFooterRefreshListener;
import com.primaryedu.widget.PullToRefreshView.OnHeaderRefreshListener;

/**
 * 通知
 *
 * @author jun.wang
 * @description
 * @data 2016年12月15日
 */
@SuppressLint("HandlerLeak")
public class InformActivity extends BaseActivity implements OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
    private MyListView myListView;
    InformAdapter adapter;
    private List<NoticeBean> lists = new ArrayList<>();
    private List<NoticeBean> tempLists = new ArrayList<>();
    private PullToRefreshView pullToRefreshView;
    private final static int REQUESTCODEHTML = 2; // "申请"返回的结果码
    private boolean fistenter = true;
    private int page = 1;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != tempLists && tempLists.size() != 0) {
                        adapter = new InformAdapter(InformActivity.this, tempLists);
                        myListView.setAdapter(adapter);
                    }
                    break;
                case 1002:
                    if (tempLists != null && tempLists.size() != 0) {
                        adapter.updateView(tempLists);
                    }
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_inform);

        init();
    }

    private void init() {
        ((TextView) findViewById(R.id.title)).setText("通知");
        findViewById(R.id.back).setOnClickListener(this);
        myListView = (MyListView) this.findViewById(R.id.listView);
        myListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
//				Intent intent = new Intent(InformActivity.this , InformDetailActivity.class) ;
//				intent.putExtra("contentStr", lists.get(position).getContent()) ;
//				intent.putExtra("dateStr", lists.get(position).getCreateDate()) ;
//				intent.putExtra("noticeid", lists.get(position).getId()) ;
//				startActivity(intent);
                StringBuilder builder = new StringBuilder();
                builder.append(Contants.notice_api).append(tempLists.get(position).getId());
                System.out.println("builder==" + builder.toString());

                Intent intent = new Intent(InformActivity.this, HtmlActivity.class);
                intent.putExtra("titleStr", "通知详情");
                intent.putExtra("urlStr", builder.toString());
                intent.putExtra("noticeid", tempLists.get(position).getId());
                startActivityForResult(intent, REQUESTCODEHTML);
//				startActivity(intent);
            }
        });

        pullToRefreshView = (PullToRefreshView) this.findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
        requestData(fistenter);
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_inform;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.back:
                Intent intent = getIntent();
                setResult(3, intent);
                finish();
                break;

            default:
                break;
        }
    }

    private void requestData(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        page = 1;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getNotice,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("getNotice==" + response);
                        dismissLoading();
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                lists = new Gson().fromJson(listStr,
                                        new TypeToken<List<NoticeBean>>() {
                                        }.getType());
                                tempLists.clear();
                                tempLists.addAll(lists);
                                handler.sendEmptyMessage(1001);
                                System.out.println("getNotice==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                map.put("userid", GlobalData.getUserId(getApplicationContext()));
//		            System.out.println("getinforuserid======="+GlobalData.getUserId(getApplicationContext()));
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void requestNoticemorelist() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getNotice,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=informmorelist=" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");
                                    System.out.println("response=listStr=" + listStr);
                                    lists = new Gson().fromJson(listStr,
                                            new TypeToken<List<NoticeBean>>() {
                                            }.getType());

                                    tempLists.addAll(lists);
                                    handler.sendEmptyMessage(1002);
                                } else {
//									if (listStr == null){
                                    showToast("已经加载完全部数据！");
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                map.put("userid", GlobalData.getUserId(getApplicationContext()));
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                requestNoticemorelist();
                pullToRefreshView.onFooterRefreshComplete();
            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestData(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(InformActivity.this, "数据刷新完成!", 0).show();
            }

        }, 1500);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 3) {
            if (requestCode == REQUESTCODEHTML) {
                requestData(false);
            }
        }
    }
}
